package com.yantong.controller;

import com.yantong.constant.CenterStatus;
import com.yantong.pojo.AmountLog;
import com.yantong.pojo.Centre;
import com.yantong.pojo.CentreAmount;
import com.yantong.pojo.Industry;
import com.yantong.service.CentreCategoryService;
import com.yantong.service.CentreService;
import com.yantong.service.IndustryService;
import com.yantong.annotation.Log;
import com.yantong.constant.BusinessCode;
import com.yantong.constant.CentreType;
import com.yantong.exception.BDException;
import com.yantong.result.ResultVo;
import com.yantong.utils.HttpContextUtils;
import com.yantong.utils.IPUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ShiroUtils;
import com.yantong.pojo.ProjectExp;
import com.yantong.pojo.vo.ProjectExpVo;
import com.yantong.service.ProjectExpService;
import com.yantong.pojo.Member;
import com.yantong.service.MemberService;
import com.yantong.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 商户控制类
 *
 * @author kanghaixin
 * @date 2018/8/24.16:22
 */
@Controller
@RequestMapping("/centre/manage")
public class CentreController extends BaseController {

    private static final String prefix = "centre/manage";

    @Autowired
    private CentreService centreService;

    @Autowired
    private CentreCategoryService centreCategoryService;
    
    @Autowired
    private MemberService memberService;
    @Autowired
    private ProjectExpService projectExpService;
    @Autowired
    private IndustryService industryService;

    /**
     * 商户列表界面
     *
     * @return
     */
    @GetMapping()
    @RequiresPermissions("centre:manage:manage")
    public String centres() {
        return prefix + "/centres";
    }

    /**
     * 选择商户界面
     *
     * @return
     */
    @GetMapping("chooseCentre")
    @RequiresPermissions("centre:manage:manage")
    public String chooseCentre() {
        return prefix + "/chooseCentre";
    }

    /**
     * 商户列表数据
     *
     * @param name
     * @param type
     * @param status
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("centre:manage:manage")
    public PageUtils<Centre> listCentres(String name, String type, String status, int offset, int limit) {
        return centreService.listCentres(getUser(),name, type, status, offset, limit);
    }

    /**
     * 选择商户列表数据
     *
     * @param queryItem 关键字
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/chooseCentreTable")
    @RequiresPermissions("centre:manage:manage")
    public PageUtils<Centre> chooseCentreTable(String queryItem, int offset, int limit) {
        return centreService.chooseCentreTable(queryItem, offset, limit);
    }

    /**
     * 商户添加界面
     *
     * @return
     */
    @Log(module = "商户管理", operation = "添加商户")
    @RequiresPermissions("centre:manage:add")
    @GetMapping("/add")
    public String add(Model model) {
    	PageUtils<ProjectExp> list =  projectExpService.listProjectExp(null,0,0);
        model.addAttribute("category", centreCategoryService.listCategorys(0L));
        model.addAttribute("projectexp",list.getRows());
        model.addAttribute("centreName",getUsername());
        return prefix + "/add";
    }

    /**
     * 检查商户名称是否存在
     *
     * @param name
     * @return
     */
    @PostMapping("/checkName")
    @ResponseBody
    public Boolean checkCentreName(String name) {
        if (StringUtils.isEmpty(name)) {
            return true;
        }
        return centreService.checkName(name);
    }

    /**
     * 商户新增
     *
     * @param centre
     * @return
     */
    @Log(module = "商户管理", operation = "添加商户")
    @ResponseBody
    @RequiresPermissions("centre:manage:add")
    @PostMapping("/save")
    public ResultVo save(Centre centre, String areas,Long referrals) {
//        String centreName = getCentreName();
//        if( StringUtils.isEmpty(centreName) || !centreName.equals("admin")){
//            centre.setDeductionRatio(null);
//            centre.setOfflineDeductionRatio(null);
//        }
        if (centre == null) {
            return ResultVo.error();
        }
        if(centre.getMid() != null) {
	    	//商户用户
	        Centre centreMember = centreService.selectByMid(centre.getMid());
		    	if(centreMember != null) {
		    		 return ResultVo.error("用户已绑定");
		    	}
        }
        //后天添加设置为已支付
        centre.setPayStatus(2);
        //设置为审核
        centre.setStatus("2");
        if(centre.getProjectexpId() != null) {
            ProjectExpVo record = new ProjectExpVo();
            record.setId(centre.getProjectexpId());
            ProjectExp projectExp=  projectExpService.listProjectExp(record);
            centre.setProjectexpName(projectExp.getName());
            centre.setProjectexpPrice(projectExp.getPrice());
        }
        //后台添加的商户账号，有效期设置为1年
        centre.setExpiredDate(DateUtil.getAddDayDate(new Date(),365));
        centre.setSaleAreas(areas);
        centre.setRenewMid(1L);



        if (CentreType.COMPANY.getCode().equals(centre.getType())) {
            /**公司需校验营业执照等**/
            if (StringUtils.isEmpty(centre.getBusiLicense())) {
                return ResultVo.error(BusinessCode.BUSINESS_LICENSE_NULL);
            }
            if (StringUtils.isEmpty(centre.getBusiCategory())) {
                return ResultVo.error(BusinessCode.BUSINESS_CATEGORY_NULL);
            }
            if (StringUtils.isEmpty(centre.getRegistCapital())) {
                return ResultVo.error(BusinessCode.REGIST_CAPITAL_NULL);
            }
            if (centre.getRegistDate() == null) {
                return ResultVo.error(BusinessCode.REGIST_DATE_NULL);
            }
        }
        if (centreService.save(centre) < 1) {
            return ResultVo.error();
        }else {

            //添加平台行业数据给商户
            HashMap hashMap = new HashMap();
            hashMap.put("centreId",null);
            List<Industry> industryList = industryService.selectByList(hashMap);
            if(!CollectionUtils.isEmpty(industryList)){
                for ( Industry industry : industryList ) {
                    Industry industryNew = new Industry();
                    industryNew.setName(industry.getName());
                    industryNew.setCentreId(centre.getCentreId());
                    industryService.saveIndustry(industryNew);
                }
            }

        }
        return ResultVo.ok();
    }


    /**
     * 商户编辑
     *
     * @param centreId
     * @param model
     * @return
     */
    @RequiresPermissions("centre:manage:edit")
    @GetMapping("/edit/{centreId}")
    public String edit(@PathVariable Long centreId, Model model) {
        model.addAttribute("centre", centreService.getByKey(centreId));
        model.addAttribute("category", centreCategoryService.listCategorys(0L));
        model.addAttribute("centreName",getUsername());
        return prefix + "/edit";
    }

    /**
     * 商户更新
     *
     * @param centre
     * @return
     */
    @Log(module = "商户管理", operation = "编辑商户")
    @ResponseBody
    @RequiresPermissions("centre:manage:edit")
    @PostMapping("/update")
    public ResultVo update(Centre centre, String areas) {
        if (centre == null || centre.getCentreId() == null) {
            return ResultVo.error();
        }
        centre.setSaleAreas(areas);
        if (centreService.updateCentre(centre) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    
    /**
     * 商户审核
     *
     * @param centre
     * @return
     */
    @Log(module = "商户管理", operation = "审核商户")
    @ResponseBody
    @RequiresPermissions("centre:manage:check")
    @PostMapping("/check")
    public ResultVo check(Long centreId) {
        if (null == centreId) {
            return ResultVo.error();
        }
        //状态设置为启用
        if (centreService.checkCentre(centreId) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    

    /**
     * 商户逻辑删除，停用
     * @param centreId
     * @return
     */
    @Log(module = "商户管理", operation = "删除商户")
    @RequiresPermissions("centre:manage:remove")
    @ResponseBody
    @PostMapping("/remove")
    public ResultVo remove(Long centreId) {
        if (centreId == null) {
            return ResultVo.error();
        }
        if (centreService.removeCentre(centreId) <1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 商户逻辑删除后恢复
     * @param centreId
     * @return
     */
    @Log(module = "商户管理", operation = "恢复商户")
    @RequiresPermissions("centre:manage:resume")
    @ResponseBody
    @PostMapping("/resume")
    public ResultVo resume(Long centreId) {
        if (centreId == null) {
            return ResultVo.error();
        }
        if (centreService.resumeCentre(centreId) <1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 批量删除项目
     * @param ids
     * @return
     */
    @Log(module = "商户管理", operation = "批量删除商户")
    @ResponseBody
    @PostMapping("/batchRemove")
    public ResultVo batchRemove(@RequestParam("ids[]") Long[] ids) {
        if (ids.length < 1) {
            return ResultVo.error();
        }
        int result = centreService.batchRemove(Arrays.asList(ids));
        if (result <0){
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 批量删除项目
     * @param ids
     * @return
     */
    @RequiresPermissions("centre:manage:hiden")
    @ResponseBody
    @PostMapping("/batchHiden")
    public ResultVo batchHiden(Integer hide,@RequestParam("ids[]") Long[] ids) {
      /*  if (ids.length < 1) {
            return ResultVo.error();
        }*/
    	 int result = 0;
    	 if (ids.length >= 1) {
    		 if(ids[0] != 0) {
    			 result = centreService.batchHiden(Arrays.asList(ids),hide);
    		 }else {
    			 result = centreService.batchAllHiden(hide);
    		 }
    	 }else {
    		 result = centreService.batchAllHiden(hide);
    	 }
        if (result <0){
            return ResultVo.error();
        }
        return ResultVo.ok();
    }
    
    /**
     * 商户详情
     * @param centreId
     * @return
     */
    @RequiresPermissions("centre:manage:detail")
    @GetMapping("/detail/{centreId}")
    public String detail(@PathVariable Long centreId, Model model) {
        model.addAttribute("centre", centreService.getByKey(centreId));
        return prefix + "/detail";
    }

    /**
     * 商户充值
     */
    @GetMapping("/recharge/{id}")
    public String recharge(@PathVariable Long id, Model model) {
        model.addAttribute("centre", centreService.getByKey(id));
        return prefix + "/recharge";
    }

    /**
     * 更新商户余额，余额流水
     * @return
     */
    @Log(module = "后台充值", operation = "后台站点充值")
    @ResponseBody
    @PostMapping("/updateMoney")
    public ResultVo updateMoney(Centre centre) {
       if (centre == null || centre.getCentreId() == null||centre.getCentreAmount().getAmount()==null) {
            return ResultVo.error();
        }
       if(centre.getCentreAmount().getAmount().compareTo(BigDecimal.ZERO)==-1){
           return ResultVo.error();
       }
        CentreAmount centreAmount=new CentreAmount();
        centreAmount.setCentreId(centre.getCentreId());
        centreAmount.setAmount(centre.getCentreAmount().getAmount());
       //0为增加余额
        int i=0;
       if("0".equals(centre.getType())){
           AmountLog al = new AmountLog();
           al.setCentreId(centreAmount.getCentreId());
           al.setMoney(centreAmount.getAmount());
           // 获取request
           HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
           if(centre.getDesc()!=null&&!"".equals(centre.getDesc())){
               al.setRemark(centre.getDesc().concat(",Ip:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
           }else{
               al.setRemark("平台给商户充值".concat(",Ip:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
           }
           al.setFlowType(5);//平台给站点充值
           
           Centre c = centreService.getByKey(centre.getCentreId());
           if (null != c.getCentreAmount()) {        	   
        	   al.setBeforeamount(c.getCentreAmount().getAmount());
        	   al.setAfteramount(c.getCentreAmount().getAmount().add(centreAmount.getAmount()));
           }
           
           i=centreService.changeAmount(centreAmount);
           centreService.saveAmountLog(al);

       }else{
           i=centreService.reduceAmount(centreAmount,centre.getDesc());
       }
       if(i<1){
           throw new BDException(BusinessCode.CENTER_AMOUNT_RECHARGE_FAIL);
       }
        return ResultVo.ok();
    }


}
